import React, { useState } from "react";
import { Card, Tag, Avatar, Progress, Tooltip, Dropdown, Menu, Modal } from "antd";
import {
  CalendarOutlined,
  UserOutlined,
  MoreOutlined,
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  ExclamationCircleOutlined
} from "@ant-design/icons";
import { useAppDispatch } from "../../../hooks/redux";
import { deleteTask } from "../../../store/projectSlice";
import type { Task } from "../../../types/project";
import { TaskStatus, TaskPriority } from "../../../types/project";
import TaskDetailModal from "./TaskDetailModal";
import CopyTaskModal from "./CopyTaskModal";
import dayjs from "dayjs";

interface TaskCardProps {
  /** 任务数据 */
  task: Task;
  /** 项目ID */
  projectId: string;
}

/**
 * 任务卡片组件 - 显示单个任务的概要信息
 * 支持点击查看详情、拖拽移动、右键操作等功能
 */
const TaskCard: React.FC<TaskCardProps> = ({ task, projectId }) => {
  const dispatch = useAppDispatch();
  const [detailVisible, setDetailVisible] = useState(false);
  const [copyVisible, setCopyVisible] = useState(false);

  /**
   * 获取任务状态标签的颜色和文本
   * @param status 任务状态
   * @returns 包含颜色和文本的对象
   */
  const getStatusTag = (status: TaskStatus) => {
    const statusMap = {
      [TaskStatus.NOT_STARTED]: { color: "#d9d9d9", text: "未开始" },
      [TaskStatus.IN_PROGRESS]: { color: "#1890ff", text: "进行中" },
      [TaskStatus.COMPLETED]: { color: "#52c41a", text: "已完成" }
    };
    return statusMap[status];
  };

  /**
   * 获取优先级标签的颜色和文本
   * @param priority 任务优先级
   * @returns 包含颜色和文本的对象
   */
  const getPriorityTag = (priority: TaskPriority) => {
    const priorityMap = {
      [TaskPriority.LOW]: { color: "#87d068", text: "低" },
      [TaskPriority.MEDIUM]: { color: "#108ee9", text: "中" },
      [TaskPriority.HIGH]: { color: "#f50", text: "高" },
      [TaskPriority.URGENT]: { color: "#ff4d4f", text: "紧急" }
    };
    return priorityMap[priority];
  };

  /**
   * 检查任务是否已过期
   * @param dueDate 截止时间
   * @returns 是否过期
   */
  const isOverdue = (dueDate?: string): boolean => {
    if (!dueDate) return false;
    return dayjs().isAfter(dayjs(dueDate)) && task.status !== TaskStatus.COMPLETED;
  };

  /**
   * 获取截止时间的显示样式
   * @param dueDate 截止时间
   * @returns 样式类名
   */
  const getDueDateStyle = (dueDate?: string): string => {
    if (!dueDate) return "text-gray-500";
    if (isOverdue(dueDate)) return "text-red-500 font-medium";

    const daysLeft = dayjs(dueDate).diff(dayjs(), "day");
    if (daysLeft <= 3) return "text-orange-500 font-medium";
    return "text-gray-500";
  };

  /**
   * 处理任务删除
   */
  const handleDeleteTask = () => {
    Modal.confirm({
      title: "确认删除任务",
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除任务 "${task.title}" 吗？此操作不可撤销。`,
      okText: "确认删除",
      cancelText: "取消",
      okType: "danger",
      onOk: () => {
        dispatch(deleteTask({ projectId, taskId: task.id }));
      }
    });
  };

  /**
   * 任务操作菜单
   */
  const taskMenu = (
    <Menu>
      <Menu.Item key="edit" icon={<EditOutlined />} onClick={() => setDetailVisible(true)}>
        编辑任务
      </Menu.Item>
      <Menu.Item key="copy" icon={<CopyOutlined />} onClick={() => setCopyVisible(true)}>
        复制任务
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="delete" icon={<DeleteOutlined />} onClick={handleDeleteTask} danger>
        删除任务
      </Menu.Item>
    </Menu>
  );

  const statusTag = getStatusTag(task.status);
  const priorityTag = getPriorityTag(task.priority);
  const overdue = isOverdue(task.dueDate);

  return (
    <>
      {/* 任务卡片主体 */}
      <Card
        size="small"
        className={`cursor-pointer transition-all duration-200 hover:shadow-md ${
          overdue ? "border-red-300 bg-red-50" : "border-gray-200 bg-white"
        }`}
        bodyStyle={{ padding: "12px" }}
        onClick={() => setDetailVisible(true)}
      >
        {/* 卡片头部：标题和操作按钮 */}
        <div className="flex items-start justify-between mb-3">
          <h4 className="text-sm font-medium text-gray-900 line-clamp-2 flex-1 mr-2">
            {task.title}
            {overdue && (
              <Tooltip title="任务已过期">
                <ExclamationCircleOutlined className="ml-1 text-red-500" />
              </Tooltip>
            )}
          </h4>
          <Dropdown overlay={taskMenu} trigger={["click"]} placement="bottomRight">
            <div className="flex-shrink-0 p-1 rounded hover:bg-gray-100" onClick={e => e.stopPropagation()}>
              <MoreOutlined className="text-gray-400 hover:text-gray-600" />
            </div>
          </Dropdown>
        </div>

        {/* 任务描述 */}
        {task.description && <p className="text-xs text-gray-600 mb-3 line-clamp-2">{task.description}</p>}

        {/* 状态和优先级标签 */}
        <div className="flex items-center gap-2 mb-3">
          <Tag color={statusTag.color} className="text-xs">
            {statusTag.text}
          </Tag>
          <Tag color={priorityTag.color} className="text-xs">
            {priorityTag.text}
          </Tag>
          {task.milestone && (
            <Tag className="text-xs bg-purple-50 text-purple-600 border-purple-200">{task.milestone}</Tag>
          )}
        </div>

        {/* 进度条（如果有子任务） */}
        {task.subTasks.length > 0 && (
          <div className="mb-3">
            <div className="flex items-center justify-between mb-1">
              <span className="text-xs text-gray-500">子任务进度</span>
              <span className="text-xs text-gray-600">{task.progress}%</span>
            </div>
            <Progress
              percent={task.progress}
              size="small"
              showInfo={false}
              strokeColor={task.progress === 100 ? "#52c41a" : "#1890ff"}
            />
          </div>
        )}

        {/* 卡片底部：负责人、截止时间等信息 */}
        <div className="flex items-center justify-between text-xs">
          {/* 负责人头像 */}
          <div className="flex items-center">
            {task.assignee ? (
              <Tooltip title={`负责人: ${task.assignee.name}`}>
                <Avatar size={20} src={task.assignee.avatar} icon={<UserOutlined />} />
              </Tooltip>
            ) : (
              <Tooltip title="未分配负责人">
                <Avatar size={20} icon={<UserOutlined />} className="bg-gray-300" />
              </Tooltip>
            )}
          </div>

          {/* 截止时间 */}
          {task.dueDate && (
            <div className={`flex items-center gap-1 ${getDueDateStyle(task.dueDate)}`}>
              <CalendarOutlined />
              <span>{dayjs(task.dueDate).format("MM/DD")}</span>
            </div>
          )}
        </div>

        {/* 子任务和卡片数量指示器 */}
        {(task.subTasks.length > 0 || task.cards.length > 0) && (
          <div className="flex items-center justify-end gap-2 mt-2 text-xs text-gray-500">
            {task.subTasks.length > 0 && (
              <span className="flex items-center gap-1">
                📋 {task.subTasks.filter(st => st.completed).length}/{task.subTasks.length}
              </span>
            )}
            {task.cards.length > 0 && <span className="flex items-center gap-1">📄 {task.cards.length}</span>}
          </div>
        )}

        {/* 标签 */}
        {task.tags && task.tags.length > 0 && (
          <div className="flex flex-wrap gap-1 mt-2">
            {task.tags.slice(0, 3).map((tag, index) => (
              <Tag key={index} className="text-xs bg-blue-50 text-blue-600 border-blue-200">
                {tag}
              </Tag>
            ))}
            {task.tags.length > 3 && (
              <Tag className="text-xs bg-gray-50 text-gray-500 border-gray-200">+{task.tags.length - 3}</Tag>
            )}
          </div>
        )}
      </Card>

      {/* 任务详情弹窗 */}
      <TaskDetailModal
        visible={detailVisible}
        onCancel={() => setDetailVisible(false)}
        task={task}
        projectId={projectId}
      />

      {/* 复制任务弹窗 */}
      <CopyTaskModal visible={copyVisible} onCancel={() => setCopyVisible(false)} task={task} projectId={projectId} />
    </>
  );
};

export default TaskCard;
